<template>
	<view class="technician-detail">
		<!-- 导航栏 -->
		<nav-bar title="技师详情"></nav-bar>

		<!-- 技师基本信息 -->
		<view class="tech-header">
			<image class="avatar" :src="techInfo.avatar" mode="aspectFill"></image>
			<view class="info">
				<view class="name-row">
					<text class="name">{{ techInfo.name }}</text>
					<text class="title">{{ techInfo.title }}</text>
				</view>
				<view class="rating">
					<text class="score">{{ techInfo.score }}分</text>
					<text class="orders">已服务{{ techInfo.orders }}人</text>
				</view>
				<view class="tags">
					<text class="tag" v-for="tag in techInfo.tags" :key="tag">{{ tag }}</text>
				</view>
			</view>
			<!-- 添加收藏按钮 -->
			<view class="collect-btn" @tap="toggleCollect">
				<text class="collect-icon">{{ isCollected ? '❤️' : '🤍' }}</text>
				<text class="collect-text">{{ isCollected ? '已收藏' : '收藏' }}</text>
			</view>
		</view>
		<!-- 技师介绍 -->
		<view class="tech-intro">
			<view class="section-title">个人简介</view>
			<text class="intro-text">{{ techInfo.introduction }}</text>
		</view>
		<button style="margin: 20rpx;padding: 30rpx;background-color: #fff;" @click="goToComment()">查看评价</button>
		<!-- 服务项目 -->
		<view class="service-list">
			<view class="section-title">服务项目</view>
			<view class="service-item" v-for="service in techInfo.services" :key="service.id">
				<image class="service-image" :src="service.image || '/static/default-service.jpg'" mode="aspectFill">
				</image>
				<view class="service-info">
					<view class="service-header">
						<text class="name">{{ service.name }}</text>
						<view class="duration">
							<image class="duration-icon" src="/static/icons/time.png"></image>
							<text>{{ service.duration }}分钟</text>
						</view>
					</view>
					<text class="desc">{{ service.desc }}</text>
					<view class="service-footer">
						<view class="price">
							<text class="symbol">¥</text>
							<text class="number">{{ service.price }}</text>
						</view>
						<view class="book-service-btn" @tap="handleBooking(service)">立即预约</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'

	export default {
		components: {
			NavBar
		},
		data() {
			return {
				techId: null,
				isCollected: false, // 添加收藏状态
				techInfo: {
					id: '',
					name: '',
					avatar: '',
					title: '',
					score: 0,
					orders: 0,
					tags: [],
					introduction: '',
					services: []
				},
				currentMT: null
			}
		},

		onLoad(options) {
			if (options.id) {
				this.techId = options.id
				// 先将技师ID设置给techInfo，确保API调用时有正确的ID
				this.techInfo.id = options.id
				// 加载技师信息
				this.loadTechInfo()
				// 检查收藏状态，使用传入的ID
				this.checkCollectStatus(options.id)
			}
		},

		methods: {
			goToComment() {
				uni.navigateTo({
					url: `/pages/technician-detail/comment?techId=${this.techId}`
				})
			},
			// 检查收藏状态
			checkCollectStatus(techId) {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null

				if (userInfoStr) {
					try {
						// 如果是字符串，尝试解析
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							// 检查是否是登录响应格式
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							// 如果不是字符串，直接使用
							userInfo = userInfoStr
						}
					} catch (e) {
						console.error('解析用户信息失败', e)
						// 解析失败时，尝试直接使用
						userInfo = userInfoStr
					}
				}

				// 确保用户已登录且有会员ID
				if (!userInfo || !userInfo.memberId) {
					console.error('未找到用户信息或会员ID');
					return;
				}

				uni.request({
					url: `${uni.$config.baseUrl}/technicianMember/technicianMember/list`,
					method: 'GET',
					data: {
						memberId: userInfo.memberId,
						technicianId: techId // 使用传入的techId参数，而不是this.techInfo.id
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							// 检查返回的列表中是否包含当前技师
							const list = res.data.rows || []
							this.currentMT = list.find(item => item.technicianId == techId)
							this.isCollected = !!this.currentMT
						}
					},
					fail: (err) => {
						console.error('获取收藏状态失败:', err)
					}
				})
			},

			// 切换收藏状态
			toggleCollect() {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null

				if (userInfoStr) {
					try {
						// 如果是字符串，尝试解析
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							// 检查是否是登录响应格式
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							// 如果不是字符串，直接使用
							userInfo = userInfoStr
						}
					} catch (e) {
						console.error('解析用户信息失败', e)
						// 解析失败时，尝试直接使用
						userInfo = userInfoStr
					}
				}

				if (this.isCollected) {
					// 取消收藏
					if (!this.currentMT || !this.currentMT.id) {
						// 如果当前收藏记录对象不存在或没有id属性
						// 重新获取收藏关系
						this.checkCollectStatus(this.techId);
						uni.showToast({
							title: '系统错误，请重试',
							icon: 'none'
						});
						return;
					}

					uni.request({
						url: `${uni.$config.baseUrl}/technicianMember/technicianMember/${this.currentMT.id}`,
						method: 'DELETE',
						success: (res) => {
							if (res.statusCode === 200 && res.data && res.data.code === 200) {
								this.isCollected = false;
								this.currentMT = null; // 清空当前收藏记录
								uni.showToast({
									title: '取消收藏成功',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: res.data.msg || '取消收藏失败',
									icon: 'none'
								})
							}
						},
						fail: () => {
							uni.showToast({
								title: '网络请求失败',
								icon: 'none'
							})
						}
					})
				} else {
					// 添加收藏
					const memberTechnician = {
						memberId: userInfo.memberId,
						technicianId: this.techId,
						collectTime: new Date().toISOString()
					}
					uni.request({
						url: `${uni.$config.baseUrl}/technicianMember/technicianMember`,
						method: 'POST',
						data: memberTechnician,
						success: (res) => {
							if (res.statusCode === 200 && res.data && res.data.code === 200) {
								this.isCollected = true;
								// 更新当前收藏关系对象
								if (res.data.data && res.data.data.id) {
									this.currentMT = res.data.data;
								} else {
									// 如果返回数据中没有对象ID，重新获取收藏关系
									this.checkCollectStatus(this.techId);
								}
								uni.showToast({
									title: '收藏成功',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: res.data.msg || '收藏失败',
									icon: 'none'
								})
							}
						},
						fail: () => {
							uni.showToast({
								title: '网络请求失败',
								icon: 'none'
							})
						}
					})
				}
			},
			// 加载技师信息
			loadTechInfo() {
				uni.showLoading({
					title: '加载中...'
				})
				// 获取技师基本信息
				uni.request({
					url: `${uni.$config.baseUrl}/technician/technician/detail`,
					method: 'GET',
					data: {
						id: this.techId
					},
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						console.log('获取技师详情成功:', res.data)
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							const tech = res.data.data

							if (tech) {
								// 从categories数组中提取categoryName作为tags
								const categoryTags = tech.categories ? tech.categories.map(category => category
									.categoryName) : []

								this.techInfo = {
									id: tech.id,
									name: tech.name || '未知技师',
									avatar: tech.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg',
									title: tech.technicianType || '高级按摩师',
									score: tech.score || 4.9,
									orders: tech.appointmentCount || 0,
									tags: categoryTags,
									introduction: tech.introduction || '暂无简介',
									services: []
								}

								// 获取技师关联的项目列表
								this.loadTechnicianProjects()
							} else {
								uni.showToast({
									title: '未找到技师信息',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: res.data.msg || '获取技师信息失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('获取技师详情失败:', err)
						uni.showToast({
							title: '网络请求失败，请检查网络',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},

			// 加载技师关联的项目列表
			loadTechnicianProjects() {
				uni.request({
					url: `${uni.$config.baseUrl}/project/project/technician/${this.techId}`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							const projects = res.data.rows || []
							// 将项目数据转换为服务列表格式
							this.techInfo.services = projects.map(project => ({
								id: project.id,
								name: project.projectName,
								image: project.imgUrls.split(',')[0],
								duration: project.duration || 60,
								desc: project.projectDesp || '暂无描述',
								price: project.price || 0
							}))
						} else {
							console.error('获取技师项目列表失败:', res.data)
						}
					},
					fail: (err) => {
						console.error('获取技师项目列表失败:', err)
					}
				})
			},

			// 跳转到预约页面
			goToBooking() {
				uni.navigateTo({
					url: `/pages/home-massage/home-massage?techId=${this.techId}`
				})
			},

			// 跳转到服务详情页面
			handleBooking(service) {
				uni.navigateTo({
					url: `/pages/service-detail/service-detail?serviceId=${service.id}&techId=${this.techInfo.id}&storeId=${this.techInfo.storeId}&fromTechDetail=true`
				})
			}
		}
	}
</script>

<style lang="scss">
	.technician-detail {
		min-height: 100vh;
		background: #F8F8F8;

		.tech-header {
			background: linear-gradient(to bottom, #FFFFFF, #F8F8F8);
			padding: 40rpx 30rpx;
			display: flex;
			position: relative;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 80rpx;
				margin-right: 30rpx;
				border: 4rpx solid #FFFFFF;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			}

			.info {
				flex: 1;

				.name-row {
					margin-bottom: 16rpx;

					.name {
						font-size: 36rpx;
						color: #333;
						font-weight: 600;
						margin-right: 20rpx;
					}

					.title {
						font-size: 26rpx;
						color: #666;
						background: rgba(43, 135, 255, 0.1);
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
					}
				}

				.rating {
					margin-bottom: 16rpx;
					display: flex;
					align-items: center;

					.score {
						font-size: 28rpx;
						color: #FF6B6B;
						margin-right: 20rpx;
						display: flex;
						align-items: center;

						&::before {
							content: '★';
							margin-right: 4rpx;
							color: #FFB800;
						}
					}

					.orders {
						font-size: 24rpx;
						color: #999;
						position: relative;
						padding-left: 20rpx;

						&::before {
							content: '';
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
							width: 2rpx;
							height: 24rpx;
							background: #EEEEEE;
						}
					}
				}

				.tags {
					display: flex;
					flex-wrap: wrap;

					.tag {
						font-size: 24rpx;
						color: #2B87FF;
						background: rgba(43, 135, 255, 0.1);
						padding: 6rpx 20rpx;
						border-radius: 20rpx;
						margin-right: 16rpx;
						margin-bottom: 12rpx;
						transition: all 0.3s;

						&:active {
							transform: scale(0.95);
						}
					}
				}
			}

			.collect-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				margin-left: 20rpx;
				padding: 16rpx 10rpx;
				border-radius: 12rpx;
				transition: all 0.3s;

				.collect-icon {
					font-size: 48rpx;
					margin-bottom: 8rpx;
				}

				.collect-text {
					font-size: 24rpx;
					color: #FF6B6B;
					font-weight: 500;
				}

				&:active {
					transform: scale(0.92);
					opacity: 0.8;
				}
			}
		}

		.tech-intro {
			background: #FFFFFF;
			margin: 20rpx;
			padding: 30rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

			.section-title {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
				margin-bottom: 20rpx;
				display: flex;
				align-items: center;

				&::before {
					content: '';
					width: 6rpx;
					height: 32rpx;
					background: #2B87FF;
					margin-right: 16rpx;
					border-radius: 3rpx;
				}
			}

			.intro-text {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
				padding: 0 10rpx;
			}
		}

		.service-list {
			background: #FFFFFF;
			margin: 20rpx;
			padding: 30rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

			.section-title {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
				margin-bottom: 20rpx;
				display: flex;
				align-items: center;

				&::before {
					content: '';
					width: 6rpx;
					height: 32rpx;
					background: #2B87FF;
					margin-right: 16rpx;
					border-radius: 3rpx;
				}
			}

			.service-item {
				padding: 30rpx;
				border-radius: 12rpx;
				background: #F8F8F8;
				margin-bottom: 20rpx;
				transition: all 0.3s;
				display: flex;
				align-items: flex-start;

				&:active {
					transform: scale(0.98);
				}

				.service-image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 12rpx;
					margin-right: 20rpx;
					background: #EEEEEE;
					flex-shrink: 0;
				}

				.service-info {
					flex: 1;
					min-width: 0; // 防止文本溢出

					.service-header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 16rpx;

						.name {
							font-size: 32rpx;
							color: #333;
							font-weight: 600;
							flex: 1;
							margin-right: 20rpx;
						}

						.duration {
							display: flex;
							align-items: center;
							background: rgba(43, 135, 255, 0.1);
							padding: 6rpx 16rpx;
							border-radius: 20rpx;
							flex-shrink: 0;

							.duration-icon {
								width: 28rpx;
								height: 28rpx;
								margin-right: 8rpx;
							}

							text {
								font-size: 26rpx;
								color: #2B87FF;
							}
						}
					}

					.desc {
						font-size: 26rpx;
						color: #666;
						margin-bottom: 24rpx;
						line-height: 1.5;
						padding: 0 10rpx;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
					}

					.service-footer {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.price {
							display: flex;
							align-items: baseline;

							.symbol {
								font-size: 24rpx;
								color: #FF6B6B;
							}

							.number {
								font-size: 36rpx;
								color: #FF6B6B;
								font-weight: 600;
							}
						}

						.book-service-btn {
							padding: 16rpx 40rpx;
							background: linear-gradient(135deg, #2B87FF, #1B6BFF);
							color: #FFFFFF;
							font-size: 28rpx;
							border-radius: 30rpx;
							box-shadow: 0 4rpx 12rpx rgba(43, 135, 255, 0.3);
							transition: all 0.3s;

							&:active {
								transform: scale(0.95);
								box-shadow: 0 2rpx 6rpx rgba(43, 135, 255, 0.2);
							}
						}
					}
				}
			}
		}
	}
</style>